﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using dotNET.Application.Infrastructure;
using dotNET.Data;
using dotNET.Domain.Entities;
using dotNET.Repository;
using dotNET.Dto;
using dotNET.Utility.Cache;

namespace dotNET.Application.App
{
    public class ModuleApp : App, IModuleApp
    {
        public IRepositoryBase<Module> _moduleRep { get; set; }
        public IModuleButtonApp _moduleButtonApp  { get; set; }

        /// <summary>
        /// Saas模块  
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        public async Task<List<Module>> GetSaasModuleListAsync(ModuleOption option = null)
        {
            return await GetListAsync( option);
        }

        /// <summary>
        /// 代理模块
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        public async Task<List<Module>> GetAgentModuleListAsync(ModuleOption option = null)
        {
            return await GetListAsync( option);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isSaas"></param>
        /// <param name="option"></param>
        /// <returns></returns>
        private async Task<List<Module>> GetListAsync( ModuleOption option)
        {
            Sql sql = Sql.Builder;
        
            if (option != null)
            {
                if (!string.IsNullOrEmpty(option.FullName))
                {
                    option.FullName = $"'%{option.FullName}%'";
                    sql = sql.Where("FullName like @FullName", new { FullName = option.FullName });
                }
                if (option.ParentId.HasValue)
                {
                    sql = sql.Where("ParentId=@ParentId", new { ParentId = option.ParentId });
                }
                if (option.IsEnabled.HasValue)
                {
                    sql = sql.Where("IsEnabled=@IsEnabled", new { IsEnabled = option.IsEnabled });
                }
            }
            var t= (await _moduleRep.GetListAsync(sql.SQL, sql.Arguments)).OrderBy(o=>o.SortCode).ToList();

            return t;
        }

        /// <summary>
        /// 菜单
        /// </summary>
        /// <param name="isSaas"></param>
        /// <returns></returns>
        public async Task<List<Module>> GetMenuCatalogListAsync()
        {
            return (await _moduleRep.GetListAsync(new {  IsMenu = false })).ToList();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<R> DeleteAsync(long id)
        {
            if (await _moduleRep.RecordCountAsync(new { ParentId = id }) > 0)
            {
                return R.Err("含有子菜单不能删除");
            }

          
                try
            {
             //   context.BeginTransaction();

                    bool b = await _moduleRep.DeleteAsync(id);
                if (!b)
                {
                    return R.Err();
                }
                await _moduleButtonApp.DeleteListAsync(id);
             //   context.Commit();
            }
            catch (Exception exc)
            {
             
                return R.Err(exc.Message);
            }
            await RemoveCacheAsync();
            return R.Suc();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<Module> GetAsync(long key)
        {
            Module m = await _moduleRep.GetAsync(key);
            return m;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="moduleEntity"></param>
        /// <returns></returns>
        public async Task<R> CreateAsync(Module moduleEntity)
        {
            moduleEntity.FullName = moduleEntity.FullName?.Trim();
            moduleEntity.UrlAddress = moduleEntity.UrlAddress?.Trim();
            moduleEntity.EnCode = "m";
            int count = await _moduleRep.RecordCountAsync(new { FullName = moduleEntity.FullName });
            if (count > 0)
            {
                return R.Err(msg: moduleEntity.FullName + " 已存在");
            }

            int r = await _moduleRep.InsertAsync(moduleEntity);
            if (r <= 0)
            {
                return R.Err();
            }
            await RemoveCacheAsync();
            return R.Suc();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="moduleEntity"></param>
        /// <returns></returns>
        public async Task<R> UpdateAsync(Module moduleEntity)
        {
            moduleEntity.FullName = moduleEntity.FullName?.Trim();
            moduleEntity.UrlAddress = moduleEntity.UrlAddress?.Trim();

            int count = await _moduleRep.RecordCountAsync("where `FullName`=@FullName and `Id`<>@Id", new { FullName = moduleEntity.FullName, Id = moduleEntity.Id });
            if (count > 0)
            {
                return R.Err(msg: moduleEntity.FullName + " 已存在");
            }
            bool b = await _moduleRep.UpdateAsync(moduleEntity);
            if (!b)
                return R.Err();

            await RemoveCacheAsync();
            return R.Suc();
        }


        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <returns></returns>
        private async Task RemoveCacheAsync()
        {
            //var cache = CacheFactory.Cache();
            //await cache.RemoveAsync("sys", "modules");
            //await cache.RemoveAsync("sys", "buttons");
        }
    }
}
